package com.sample.service;

import com.sample.service.scheduling.CronTriggerFactory;
import com.sample.service.scheduling.JobFactory;
import com.sample.service.scheduling.SchedulerFactory;
import com.sample.service.scheduling.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.JobDetailBean;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: khanhpham
 * Date: 10/25/11
 * Time: 10:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class CustomMessageListener implements MessageListener {
   @Autowired
   private SchedulerFactory schedulerFactory;
   private long counter;

   public void onMessage(Message message) {
      ObjectMessage om = (ObjectMessage) message;
      try {
         System.out.println("Message received");
         EventMetadata eventMetadata = (EventMetadata) om.getObject();
         scheduleASimpleJob(eventMetadata);
      } catch (JMSException e) {
         e.printStackTrace();
      }

      try {
         Thread.sleep(5000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }

   private void scheduleASimpleJob(final EventMetadata eventMetadata) {
      JobDetailBean jobDetail = JobFactory.createJobDetailBean("job_" + counter, SimpleJob.class);
      Map<String, Object> stringMap = new HashMap<String, Object>();
      stringMap.put("EVENT_METADATA", eventMetadata);
      jobDetail.setJobDataAsMap(stringMap);
      try {
         CronTriggerBean cronTrigger = CronTriggerFactory.createCronTriggerBean("0/5 * * * * ?", "trigger_" + counter, jobDetail);
         schedulerFactory.scheduleJob(cronTrigger);
      } catch (ParseException e) {
         e.printStackTrace();
         return;
      }
   }
}
